package org.gvp.gateway.service;

import io.netty.util.AsyncMapping;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.gvp.common.http.Result;
import org.gvp.gateway.cache.CacheHandler;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import static org.gvp.gateway.cache.CacheHandler.USER_MENU_PREFIX;

@Log4j2
@Service
@RequiredArgsConstructor
public class RootService {

    private final CacheHandler<Object> cacheHandler;
    private final PasswordEncoder passwordEncoder;
    /**
     * 检查测试服务是否正常
     */
    public Mono<Result<Boolean>> check() {
        return Mono.just(Result.ok(true));
    }

    /**
     * 密码加密
     * @param password
     */
    public String encryption(String password) {
        log.debug("加密密码: {}", password);
        if (StringUtils.hasLength(password)) {
            return this.passwordEncoder.encode(password);
        }
        return null;
    }

    /**
     * 根参数用户名,刷新指定用户的菜单显示信息
     */
    public Mono<Long> flushUserMenu(String username) {
        log.debug("刷新用户 {} 的菜单树信息", username);
        return this.cacheHandler.delete(USER_MENU_PREFIX + username);
    }

    /**
     * 刷新权限菜单树数据
     */
    public Mono<Long> flushMenuTree() {
        log.debug("刷新菜单权限树");
        return this.cacheHandler.delete(CacheHandler.MENU_RENDER_TREE);
    }

    /**
     * 刷新用户登录信息
     * @param username 登录用户名
     */
    public Mono<Long> flushLoginUser(String username) {
        log.debug("刷新用户登录信息: {}", username);
        return this.cacheHandler.deleteMore(CacheHandler.USER_LOGIN_KEY + username,CacheHandler.USER_SECURITY_KEY + username);
    }

    /**
     * 刷新角色路径权限关系
     * @param roleName 角色名
     */
    public Mono<Long> flushRolePath(String roleName) {
        log.debug("刷新角色路径权限关系: {}", roleName);
        return this.cacheHandler.delete(CacheHandler.ROLE_PATH_PREFIX + roleName);
    }
}
